// 基础配置接口
export interface HttpConfig {
  headers?: Record<string, string>
  params?: Record<string, any>
  timeout?: number
  baseURL?: string
}

// API 响应接口
export interface ApiResponse<T = any> {
  code: number
  message: string
  data: T
  success: boolean
}

// 在 SSR 环境中，不导入 axios，使用 mock 实现
// 在浏览器环境中，动态导入 axios
let service: any = null

async function getAxiosInstance() {
  if (!service) {
    // 检查是否在浏览器环境
    if (typeof window !== 'undefined') {
      // 浏览器环境：导入真实的 axios
      const axios = await import('axios')
      service = axios.default.create({
        baseURL: import.meta.env.VITE_APP_BASE_API || 'https://cms-test.cedim.cn/api/',
        timeout: 30000,
        headers: {
          'Content-Type': 'application/json;charset=utf-8'
        }
      })

      // 请求拦截器
      service.interceptors.request.use(
        (config: any) => {
          console.log('Request:', config)
          return config
        },
        (error: any) => {
          console.error('Request Error:', error)
          return Promise.reject(error)
        }
      )

      // 响应拦截器
      service.interceptors.response.use(
        (response: any) => {
          console.log('Response:', response)
          const { data } = response
          if (response.status === 200 && data) {
            return response
          } else {
            console.error('Business Error:', data.message)
            return Promise.reject(new Error(data.message || '请求失败'))
          }
        },
        (error: any) => {
          console.error('Response Error:', error)
          let message = '网络错误'
          if (error.response) {
            const { status, data } = error.response
            switch (status) {
              case 401:
                message = '未授权，请重新登录'
                break
              case 403:
                message = '拒绝访问'
                break
              case 404:
                message = '请求地址出错'
                break
              case 500:
                message = '服务器内部错误'
                break
              default:
                message = data?.message || `连接错误${status}`
            }
          } else if (error.request) {
            message = '网络连接异常'
          } else {
            message = error.message || '请求失败'
          }
          console.error('HTTP Error:', message)
          return Promise.reject(error)
        }
      )
    } else {
      // SSR 环境：返回 mock 实现
      service = {
        get: () => Promise.resolve({ data: null, status: 200 }),
        post: () => Promise.resolve({ data: null, status: 200 }),
        put: () => Promise.resolve({ data: null, status: 200 }),
        delete: () => Promise.resolve({ data: null, status: 200 }),
        patch: () => Promise.resolve({ data: null, status: 200 }),
        request: () => Promise.resolve({ data: null, status: 200 }),
        interceptors: {
          request: { use: () => {}, eject: () => {} },
          response: { use: () => {}, eject: () => {} }
        }
      }
    }
  }

  return service
}

// 导出 http 实例 - 使用同步方式以保持兼容性
let cachedService: any = null

function getService() {
  if (!cachedService) {
    // 在浏览器环境中，立即初始化
    if (typeof window !== 'undefined') {
      // 异步初始化，但返回一个 proxy
      getAxiosInstance().then(s => { cachedService = s })

      // 返回一个 proxy，延迟调用
      return new Proxy({}, {
        get: (target, prop) => {
          if (cachedService) {
            return (cachedService as any)[prop]
          }
          // 如果还没初始化，返回一个函数
          return (...args: any[]) => {
            return getAxiosInstance().then((s: any) => (s as any)[prop](...args))
          }
        }
      })
    } else {
      // SSR 环境：返回 mock
      cachedService = {
        get: () => Promise.resolve({ data: null, status: 200 }),
        post: () => Promise.resolve({ data: null, status: 200 }),
        put: () => Promise.resolve({ data: null, status: 200 }),
        delete: () => Promise.resolve({ data: null, status: 200 }),
        patch: () => Promise.resolve({ data: null, status: 200 }),
        request: () => Promise.resolve({ data: null, status: 200 }),
        interceptors: {
          request: { use: () => {}, eject: () => {} },
          response: { use: () => {}, eject: () => {} }
        }
      }
    }
  }

  return cachedService
}

// 导出 http 实例
export const http = getService()
export default getService()
